import wtforms
from flask_wtf.file import FileAllowed, FileSize

from wtforms.validators import Email, Length, EqualTo, InputRequired

from app import UserModel, EmailCaptchaModel
from ..exts import db

class RegisterForm(wtforms.Form):
    email=wtforms.StringField(validators=[Email(message='邮箱格式错误！！！')])
    captcha=wtforms.StringField(validators=[Length(min=6,max=6,message='验证码格式错误！！！')])
    username=wtforms.StringField(validators=[Length(min=3,max=20,message='用户名格式错误！！！')])
    job=wtforms.StringField(validators=[Length(min=1,max=20,message='职业格式错误！！！')])
    profile=wtforms.StringField(validators=[Length(min=3,message='简介格式错误！！！')])
    phone=wtforms.StringField(validators=[Length(min=11,max=11,message='手机号格式错误！！！')])
    password=wtforms.StringField(validators=[Length(min=6,max=200,message='密码格式错误！！！')])
    password_confirm=wtforms.StringField(validators=[EqualTo('password')])
    # 自定义验证
    def validate_email(self,field):
        email=field.data
        user=UserModel.query.filter_by(email=email).first()
        if user:
            raise wtforms.ValidationError(message='该邮箱已被注册！！！')
    def validate_captcha(self,field):
        captcha=field.data
        email=self.email.data
        captcha_model=EmailCaptchaModel.query.filter_by(email=email,captcha=captcha).first()
        if not captcha_model:
            raise wtforms.ValidationError(message='该邮箱或验证码错误！！！')
        else:
            db.session.delete(captcha_model)
            db.session.commit()
class LoginForm(wtforms.Form):
    email=wtforms.StringField(validators=[Email(message='邮箱格式错误！！！')])
    password=wtforms.StringField(validators=[Length(min=6,max=200,message='密码格式错误！！！')])

# 博客

class BlogForm(wtforms.Form):
    title=wtforms.StringField(validators=[Length(min=1,max=20,message='标题格式错误！！！')])
    content=wtforms.StringField(validators=[Length(min=3,message='内容格式错误！！！')])
    categorie_id=wtforms.StringField(validators=[InputRequired(message='未选择博客分类！！！')])
    author_id=wtforms.StringField(validators=[InputRequired(message='未登录！！！')])
    tags=wtforms.StringField(validators=[Length(min=1,message='标签格式错误！！！')])
    picture=wtforms.FileField('封面图片',validators=[FileAllowed(['jpg','png','jpeg','gif'],message='仅支持JPG/PNG/JPEG/GIF格式'),
                                                     FileSize(max_size=3*1024*1024,message='图片大小不能超过3MB')])


class CommentForm(wtforms.Form):
    nickname=wtforms.StringField(validators=[Length(min=1,max=20,message='昵称格式错误，1-20！！！')])
    content=wtforms.StringField(validators=[Length(min=3,message='留言格式错误！！！')])
